package com.geovis.emergency.spd.biz.app.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geovis.common.auth.util.AuthUtil;
import com.geovis.emergency.spd.biz.app.mapper.AppMsgMapper;
import com.geovis.emergency.spd.biz.app.mapper.AppMsgUserMapper;
import com.geovis.emergency.spd.biz.app.service.AppMsgService;
import com.geovis.emergency.spd.biz.system.service.ISystemUserService;
import com.geovis.emergency.spd.entity.app.dto.AppMsgDto;
import com.geovis.emergency.spd.entity.app.dto.SmsSendDetailDto;
import com.geovis.emergency.spd.entity.app.dto.SmsSendDetailVarsDto;
import com.geovis.emergency.spd.entity.app.entity.AppMsg;
import com.geovis.emergency.spd.entity.app.entity.AppMsgUser;
import com.geovis.emergency.spd.entity.command.entity.OdsZgtfwTyphoon;
import com.geovis.emergency.spd.entity.system.entity.SystemUser;
import com.geovis.oauth2.sdk.dto.ApiSmsSend;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class AppMsgServiceImpl extends ServiceImpl<AppMsgMapper, AppMsg> implements AppMsgService {

    private final AppMsgUserMapper appMsgUserMapper;

    private final ISystemUserService systemUserService;

    private final String appid="57404";
    private final String project="QxlPA2";
    private final String signature="4ade370a949c1f98dedd2c77d31dedc2";
    private final String smsUrl="https://api-v4.mysubmail.com/sms/multixsend";

    @Override
    public void saveMsg(AppMsgDto appMsgDto) {
        AppMsg appMsg=new AppMsg();
        BeanUtils.copyProperties(appMsgDto,appMsg);
        this.save(appMsg);
        if("2".equals(appMsg.getType()))
        {
            appMsgDto.getUserIds().stream().forEach(userId->{
                AppMsgUser appMsgUser=new AppMsgUser();
                appMsgUser.setAppMsgId(appMsg.getId())
                        .setUserId(userId);
                appMsgUserMapper.insert(appMsgUser);

            });
            SystemUser systemUser=systemUserService.getById(AuthUtil.getCurrentUserId());
            String sendUser=systemUser.getRealName();
            LocalDate now=LocalDate.now();
            String content=now.toString()+"发布信息，“"+appMsgDto.getTitle()+"”,具体内容为："+appMsgDto.getContent();
            if(!CollectionUtils.isEmpty(appMsgDto.getPhones()))
            {
                //如果是输入手机号（直接发送短信）
                List<SmsSendDetailDto> dtos=appMsgDto.getPhones().stream().map(phone->{

                    SmsSendDetailDto detailDto=new SmsSendDetailDto();
                    detailDto.setTo(phone);
                    detailDto.setName(phone);
                    SmsSendDetailVarsDto varsDto=new SmsSendDetailVarsDto();
                    varsDto.setSendname(sendUser);
                    varsDto.setContent(content);
                    detailDto.setVars(varsDto);
                    return detailDto;

                }).collect(Collectors.toList());
                sendSms(dtos);
                log.info("发送短信成功");
            }


        }
    }

    private void sendSms(List<SmsSendDetailDto> dtos)
    {
        String multi= JSONUtil.toJsonStr(dtos);
        //url=url+"appid="+appid+"&project="+project+"&signature="+signature+"&multi="+multi;

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.MULTIPART_FORM_DATA);
        RestTemplate restTemplate=new RestTemplate();
        MultiValueMap<String,String> reqMap = new LinkedMultiValueMap<>();
        reqMap.add("appid", appid);
        reqMap.add("project", project);
        reqMap.add("signature", signature);
        reqMap.add("multi", multi);

        HttpEntity<MultiValueMap<String,String>> entity = new HttpEntity<>(reqMap,header);
        ResponseEntity<String> response=restTemplate.exchange(smsUrl, HttpMethod.POST, entity,String.class);
        if(response.getStatusCode()!= HttpStatus.OK)
        {
            log.error("请求失败！");
            log.error("body:"+response.getBody());
            return;
        }
    }

    @Override
    public List<AppMsg> getList() {
        List<AppMsg> list=new ArrayList<>();
        List<AppMsg> broadcast=this.list(Wrappers.lambdaQuery(AppMsg.class)
                .eq(AppMsg::getType, "1"));
        list.addAll(broadcast);

        List<AppMsgUser> msgUsers=appMsgUserMapper.selectList(Wrappers.lambdaQuery(AppMsgUser.class)
                .eq(AppMsgUser::getUserId, AuthUtil.getCurrentUserId()));

        if(!CollectionUtils.isEmpty(msgUsers))
        {
            List<String> ids=msgUsers.stream().map(AppMsgUser::getAppMsgId).collect(Collectors.toList());
            List<AppMsg> personMsg=this.listByIds(ids);
            list.addAll(personMsg);
        }

        return list;
    }
}
